<style scoped>
  .example-content {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
</style>
<template>
  <ion-tabs>
    <ion-tab tab="home">
      <div id="home-page">
      <ion-page>
    <!-- 主头部 -->
    <ion-header>
      <ion-toolbar>
        <ion-title>首页</ion-title>
      </ion-toolbar>
      
      <!-- 倒计时显示区域 -->
      <div v-if="countdownActive" class="countdown-header">
        <div class="time-display">
          <div class="time-unit">
            <span class="time-value">{{ displayDays }}</span>
            <span class="time-label">天</span>
          </div>
          <div class="time-unit">
            <span class="time-value">{{ displayHours }}</span>
            <span class="time-label">时</span>
          </div>
          <div class="time-unit">
            <span class="time-value">{{ displayMinutes }}</span>
            <span class="time-label">分</span>
          </div>
          <div class="time-unit">
            <span class="time-value">{{ displaySeconds }}</span>
            <span class="time-label">秒</span>
          </div>
        </div>
        <ion-button size="small" color="danger" @click="stopCountdown">停止</ion-button>
      </div>
    </ion-header>
    
    <!-- 固定工具栏 -->
    <ion-header slot="fixed">
      <ion-toolbar class="fixed-toolbar">
        <ion-buttons slot="start">
          <ion-button @click="toggleView">
            <ion-icon :icon="viewMode === 'grid' ? gridOutline : grid"></ion-icon>
            <ion-label>{{ viewMode === 'grid' ? '瀑布流' : '网格' }}</ion-label>
          </ion-button>
        </ion-buttons>
        
        <!-- 搜索框 -->
        <div class="search-container">
          <ion-searchbar 
            v-model="searchQuery"
            @ionInput="handleSearchInput"
            @ionClear="clearSearch"
            @keyup.enter="applySearch"
            placeholder="搜索图片..."
            animated
            class="custom-searchbar"
          ></ion-searchbar>
          
          <!-- 搜索建议 -->
          <div v-if="showSuggestions && searchQuery" class="suggestions-box">
            <div 
              v-for="(suggestion, index) in filteredSuggestions" 
              :key="index"
              class="suggestion-item"
              @click="selectSuggestion(suggestion)"
            >
              <ion-icon :icon="historyIcon"></ion-icon>
              <span>{{ suggestion }}</span>
            </div>
            <div v-if="filteredSuggestions.length === 0" class="no-suggestions">
              无匹配结果
            </div>
          </div>
        </div>
        
        <ion-buttons slot="end">
          <ion-button @click="toggleSelectMode" :disabled="items.length === 0">
            <ion-icon :icon="isSelecting ? checkmarkCircle : checkmarkCircleOutline"></ion-icon>
            <ion-label>{{ isSelecting ? '取消选择' : '选择' }}</ion-label>
          </ion-button>
          
          <!-- 倒计时功能按钮 -->
          <ion-button @click="openCountdownModal">
            <ion-icon :icon="timeOutline"></ion-icon>
            <ion-label>倒计时</ion-label>
          </ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>
    
    <ion-content @ionScroll="handleScroll" ref="contentElement">
      <!-- 卡片容器 -->
      <div class="card-container" :class="viewMode" ref="cardContainer">
        <ion-card 
          v-for="item in filteredItems" 
          :key="item.id"
          class="gallery-card"
          :class="{ 
            'selected': item.selected, 
            'not-selected': !item.selected && isSelecting,
            'select-mode': isSelecting
          }"
          @click="handleCardClick(item.id)"
          @touchstart.passive="startLongPress(item.id)"
          @touchend.passive="endLongPress"
          @touchcancel.passive="endLongPress"
          :style="getCardStyle(item)"
        >
          <ion-checkbox 
            v-if="isSelecting"
            slot="start" 
            :checked="item.selected" 
            @click.stop
          ></ion-checkbox>
          <div class="image-container" :data-id="item.id">
            <div v-if="item.loading" class="loading-overlay">
              <ion-spinner></ion-spinner>
            </div>
            <img
              v-if="item.visible"
              :src="item.displaySrc"
              :alt="'Gallery image ' + item.id"
              @load="handleImageLoad(item.id, $event)"
              @error="handleImageError(item.id)"
              class="lazy-image"
              :class="{ 'loaded': item.loaded }"
            />
            <div v-else class="skeleton-placeholder" :style="{ height: item.height + 'px' }"></div>
          </div>
        </ion-card>
      </div>

      <!-- 加载指示器 -->
      <ion-item v-if="isLoading" class="ion-text-center">
        <ion-spinner></ion-spinner>
        <ion-label>加载中...</ion-label>
      </ion-item>

      <!-- 图片预览模态框 - 电视机效果 -->
      <ion-modal :is-open="previewVisible" @didDismiss="previewVisible = false">
        <div class="tv-preview-container">
          <div class="tv-frame">
            <!-- 标签显示区域 -->
              <div class="tags-container">
                <ion-chip v-for="(tag, index) in currentItemTags" :key="index" color="primary">
                  <ion-label>{{ tag }}</ion-label>
                </ion-chip>
              </div>
            <!-- 电视机屏幕区域 -->
            <div class="tv-screen">
              <img 
                :src="previewImage" 
                alt="Preview image" 
                class="tv-image"
                :class="{ 'loaded': previewLoaded }"
                @load="previewLoaded = true"
                @error="handlePreviewImageError"
              />
              <ion-spinner v-if="!previewLoaded" class="tv-spinner"></ion-spinner>
              
              <!-- 电视机时间显示 -->
              <div class="tv-time">{{ currentTime }}</div>
              
              
            </div>
            
            <!-- 电视机底座 -->
            <div class="tv-stand"></div>
          </div>
          
          <!-- 电视机控制按钮 -->
          <div class="tv-controls">
            <ion-button class="tv-button" @click="previewVisible = false">
              <ion-icon :icon="closeCircle"></ion-icon>
              <ion-label>关闭</ion-label>
            </ion-button>
          </div>
        </div>
      </ion-modal>

      <!-- 倒计时配置模态框 -->
      <ion-modal :is-open="countdownModalVisible" @didDismiss="countdownModalVisible = false">
        <div class="countdown-modal-content">
          <ion-toolbar>
            <ion-title>设置倒计时</ion-title>
            <ion-buttons slot="end">
              <ion-button @click="countdownModalVisible = false">关闭</ion-button>
            </ion-buttons>
          </ion-toolbar>
          
          <ion-content class="countdown-content">
            <!-- 模式选择 -->
            <ion-segment v-model="countdownMode">
              <ion-segment-button value="single">
                <ion-label>单目标倒计时</ion-label>
              </ion-segment-button>
              <ion-segment-button value="dual">
                <ion-label>双目标倒计时</ion-label>
              </ion-segment-button>
            </ion-segment>

            <!-- 单目标倒计时 -->
            <div v-if="countdownMode === 'single'" class="countdown-option">
              <ion-item>
                <ion-label position="stacked">选择目标时间</ion-label>
                <ion-datetime 
                  v-model="singleTargetTime" 
                  display-format="YYYY/MM/DD HH:mm" 
                  minute-values="0,5,10,15,20,25,30,35,40,45,50,55"
                ></ion-datetime>
              </ion-item>
              
              <ion-button expand="block" @click="startSingleCountdown" :disabled="!singleTargetTime">
                开始倒计时
              </ion-button>
            </div>

            <!-- 双目标倒计时 -->
            <div v-if="countdownMode === 'dual'" class="countdown-option">
              <ion-item>
                <ion-label position="stacked">起始时间</ion-label>
                <ion-datetime 
                  v-model="startTime" 
                  display-format="YYYY/MM/DD HH:mm" 
                  minute-values="0,5,10,15,20,25,30,35,40,45,50,55"
                ></ion-datetime>
              </ion-item>
              
              <ion-item>
                <ion-label position="stacked">结束时间</ion-label>
                <ion-datetime 
                  v-model="endTime" 
                  display-format="YYYY/MM/DD HH:mm" 
                  minute-values="0,5,10,15,20,25,30,35,40,45,50,55"
                ></ion-datetime>
              </ion-item>
              
              <ion-button expand="block" @click="startDualCountdown" :disabled="!startTime || !endTime">
                开始倒计时
              </ion-button>
            </div>
          </ion-content>
        </div>
      </ion-modal>
    </ion-content>

    <!-- 底部工具栏 -->
    <ion-footer>
      <ion-toolbar>
        <ion-buttons>
          <ion-button @click="addItem('start')" :disabled="isSelecting">
            <ion-icon :icon="add"></ion-icon>
            <ion-label>前置添加</ion-label>
          </ion-button>
          <ion-button @click="addItem('end')" :disabled="isSelecting">
            <ion-icon :icon="add"></ion-icon>
            <ion-label>后置添加</ion-label>
          </ion-button>
          <ion-button @click="deleteSelected" :disabled="!hasSelected || !isSelecting">
            <ion-icon :icon="trash"></ion-icon>
            <ion-label>删除选中</ion-label>
          </ion-button>
          <ion-button @click="deleteAll" :disabled="items.length === 0 || isSelecting">
            <ion-icon :icon="trash"></ion-icon>
            <ion-label>全部删除</ion-label>
          </ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-footer>
  </ion-page>
    </div>
    </ion-tab>
    <ion-tab tab="shopping">
      <div id="shopping-page">
        <ion-header>
          <ion-toolbar>
            <ion-title>购物车</ion-title>
          </ion-toolbar>
        </ion-header>
        <ion-content>
          <div class="example-content">购物车</div>
        </ion-content>
      </div>
    </ion-tab>
    <ion-tab tab="library">
      <div id="library-page">
        <ion-header>
          <ion-toolbar>
            <ion-title>Library</ion-title>
          </ion-toolbar>
        </ion-header>
        <ion-content>
          <div class="example-content">Library content</div>
        </ion-content>
      </div>
    </ion-tab>
    <ion-tab tab="mine">
      <div id="mine-page">
        <ion-header>
          <ion-toolbar>
            <ion-title>我的</ion-title>
          </ion-toolbar>
        </ion-header>
        <ion-content>
          <div class="example-content">我的</div>
        </ion-content>
      </div>
    </ion-tab>

    <ion-tab-bar slot="bottom">
      <ion-tab-button tab="home">
        <ion-icon :icon="home" />
        首页
      </ion-tab-button>
      <ion-tab-button tab="shopping">
        <ion-icon :icon="bagHandle" />
        购物车
      </ion-tab-button>
      <ion-tab-button tab="library">
        <ion-icon :icon="library" />
        Library
      </ion-tab-button>
      <ion-tab-button tab="mine">
        <ion-icon :icon="accessibility" />
        我的
      </ion-tab-button>
    </ion-tab-bar>
  </ion-tabs>
</template>

<script lang="ts">
  import {
    IonTabs, IonTab,
    IonToolbar,IonTabBar,
    IonTabButton,IonContent,
    IonHeader,IonTitle,
    IonIcon,IonPage, 
    IonButton,  IonCheckbox, IonModal, 
    IonSpinner, IonLabel, IonItem, 
    IonButtons, IonCard, IonFooter,
    IonSegment, IonSegmentButton,
    IonDatetime, toastController, 
    IonChip, IonSearchbar,
  
  } from '@ionic/vue';

  import { library, search ,  grid, gridOutline, checkmarkCircle, checkmarkCircleOutline, 
  add, trash, timeOutline, closeCircle, time,} from 'ionicons/icons';
  import { defineComponent, ref, onMounted, watch, nextTick, onUnmounted } from 'vue';
import { bagHandle ,home,accessibility} from 'ionicons/icons';
  // 使用更可靠的图片源
function getRandomImageUrl(width: number = 400, height: number = 500) {
  // 使用稳定的图片源服务
  const randomIds = [
    100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
    200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
    300, 301, 302, 303, 304, 305, 306, 307, 308, 309,
    400, 401, 402, 403, 404, 405, 406, 407, 408, 409,
    500, 501, 502, 503, 504, 505, 506, 507, 508, 509,
    600, 601, 602, 603, 604, 605, 606, 607, 608, 609,
    700, 701, 702, 703, 704, 705, 706, 707, 708, 709,
    800, 801, 802, 803, 804, 805, 806, 807, 808, 809,
    900, 901, 902, 903, 904, 905, 906, 907, 908, 909
  ];
  
  const randomIndex = Math.floor(Math.random() * randomIds.length);
  return `https://picsum.photos/id/${randomIds[randomIndex]}/${width}/${height}`;
}

// 修复：使用更可靠的默认图片源
const DEFAULT_IMAGE = "https://picsum.photos/id/0/400/500?blur=1";

// 图片标签库
const TAGS = [
  '风景', '动物', '建筑', '城市', '自然', 
  '山脉', '海洋', '森林', '花卉', '天空',
  '日落', '夜景', '雪景', '沙漠', '河流',
  '瀑布', '湖泊', '田野', '春天', '夏天',
  '秋天', '冬天', '野生动物', '鸟类', '昆虫'
];

// 模拟数据生成器
function generateItems(count: number, startId: number = 0) {
  return Array.from({ length: count }, (_, i) => {
    // 生成不同宽高比的图片
    const width = 400;
    const height = 300 + Math.floor(Math.random() * 300);
    
    // 随机选择3-5个标签
    const tags = [];
    const tagCount = 3 + Math.floor(Math.random() * 3);
    const shuffledTags = [...TAGS].sort(() => 0.5 - Math.random());
    for (let j = 0; j < tagCount; j++) {
      tags.push(shuffledTags[j]);
    }
    
    return {
      id: `item-${startId + i}`,
      src: getRandomImageUrl(width, height),
      displaySrc: getRandomImageUrl(width, height), // 初始设置显示图片
      selected: false,
      height: 200, // 默认高度
      loaded: false,
      loading: false,
      visible: true, // 默认可见
      naturalWidth: width,
      naturalHeight: height,
      retryCount: 0,
      tags: tags // 添加标签属性
    };
  });
}
  export default defineComponent({
    components: { IonTabs, IonTab, IonToolbar, IonTabBar, IonTabButton,
    IonContent, IonHeader, IonTitle, IonIcon,
    IonPage,IonButton,  IonCheckbox, IonModal, 
    IonSpinner, IonLabel, IonItem,
    IonButtons, IonCard, IonFooter,
    IonSegment, IonSegmentButton,
    IonDatetime
     },
     setup() {
    // 画廊状态管理
    const items = ref(generateItems(14)); // 初始加载14张图片
    const visibleItems = ref([...items.value]);
    const filteredItems = ref([...items.value]); // 用于搜索过滤
    const viewMode = ref('grid');
    const isLoading = ref(false);
    const previewVisible = ref(false);
    const previewImage = ref('');
    const previewLoaded = ref(false);
    const isSelecting = ref(false);
    const cardContainer = ref<HTMLElement | null>(null);
    const contentElement = ref<any>(null);
    const cardPositions = ref<{[key: string]: {left: number, top: number, width: number}}>({});
    const hasSelected = ref(false);
    const allLoaded = ref(false); // 标记是否已加载所有数据
    const page = ref(1); // 当前加载页码
    const currentTime = ref(''); // 电视机预览中的当前时间
    const currentItemTags = ref<string[]>([]); // 当前预览图片的标签

    // 倒计时状态管理
    const countdownModalVisible = ref(false);
    const countdownMode = ref<'single' | 'dual'>('single');
    const singleTargetTime = ref<string>('');
    const startTime = ref<string>('');
    const endTime = ref<string>('');
    const countdownInterval = ref<NodeJS.Timeout | null>(null);
    const countdownActive = ref(false);
    
    // 倒计时显示值
    const displayDays = ref(0);
    const displayHours = ref(0);
    const displayMinutes = ref(0);
    const displaySeconds = ref(0);
    
    // 搜索相关状态
    const searchQuery = ref('');
    const showSuggestions = ref(false);
    const searchHistory = ref<string[]>([]);
    const allSuggestions = ref<string[]>([...TAGS]); // 所有建议标签
    const filteredSuggestions = ref<string[]>([]);
    const searchTimeout = ref<NodeJS.Timeout | null>(null);

    // 图标
    const icons = {
      grid, gridOutline, checkmarkCircle, checkmarkCircleOutline, 
      add, trash, timeOutline, closeCircle,
      historyIcon: time
    };

    // 获取卡片样式
    const getCardStyle = (item: any) => {
      if (viewMode.value === 'waterfall' && cardPositions.value[item.id]) {
        return {
          position: 'absolute',
          left: `${cardPositions.value[item.id].left}px`,
          top: `${cardPositions.value[item.id].top}px`,
          width: `${cardPositions.value[item.id].width}px`,
          transition: 'all 0.3s ease'
        };
      }
      return {};
    };

    // 切换视图模式
    const toggleView = () => {
      viewMode.value = viewMode.value === 'grid' ? 'waterfall' : 'grid';
      nextTick(() => {
        if (viewMode.value === 'waterfall') {
          arrangeWaterfallItems();
        } else {
          resetGridLayout();
        }
      });
    };

    // 重置网格布局
    const resetGridLayout = () => {
      cardPositions.value = {};
      if (cardContainer.value) {
        cardContainer.value.style.height = 'auto';
      }
    };

    // 切换选择模式
    const toggleSelectMode = () => {
      isSelecting.value = !isSelecting.value;
      if (!isSelecting.value) {
        visibleItems.value.forEach(item => {
          item.selected = false;
        });
      }
      updateHasSelected();
    };

    // 处理卡片点击
    const handleCardClick = (id: string) => {
      if (isSelecting.value) {
        const item = visibleItems.value.find(i => i.id === id);
        if (item) {
          item.selected = !item.selected;
          updateHasSelected();
        }
      } else {
        const item = visibleItems.value.find(i => i.id === id);
        if (item) {
          // 保存当前预览图片的标签
          currentItemTags.value = [...item.tags];
          showPreview(item.displaySrc || item.src);
        }
      }
    };

    // 处理预览图片错误
    const handlePreviewImageError = () => {
      previewImage.value = DEFAULT_IMAGE;
      previewLoaded.value = true;
    };

    // 开始长按
    const startLongPress = (id: string) => {
      // 长按逻辑实现
    };

    // 结束长按
    const endLongPress = () => {
      // 结束长按逻辑实现
    };

    // 更新选中状态
    const updateHasSelected = () => {
      hasSelected.value = visibleItems.value.some(item => item.selected);
    };

    // 添加项目
    const addItem = (position: 'start' | 'end') => {
      const newId = `item-${Date.now()}`;
      const width = 400;
      const height = 300 + Math.floor(Math.random() * 300);
      
      // 随机选择3-5个标签
      const tags = [];
      const tagCount = 3 + Math.floor(Math.random() * 3);
      const shuffledTags = [...TAGS].sort(() => 0.5 - Math.random());
      for (let j = 0; j < tagCount; j++) {
        tags.push(shuffledTags[j]);
      }
      
      const newItem = {
        id: newId,
        src: getRandomImageUrl(width, height),
        displaySrc: getRandomImageUrl(width, height),
        selected: false,
        height: 200,
        loaded: false,
        loading: false,
        visible: true,
        naturalWidth: width,
        naturalHeight: height,
        retryCount: 0,
        tags: tags // 添加标签属性
      };

      if (position === 'start') {
        items.value.unshift(newItem);
        visibleItems.value.unshift(newItem);
        filteredItems.value.unshift(newItem);
      } else {
        items.value.push(newItem);
        visibleItems.value.push(newItem);
        filteredItems.value.push(newItem);
      }
      
      nextTick(() => {
        if (viewMode.value === 'waterfall') {
          arrangeWaterfallItems();
        }
      });
    };

    // 删除选中项目
    const deleteSelected = () => {
      const selectedCount = visibleItems.value.filter(item => item.selected).length;
      
      if (selectedCount === 0) return;
      
      if (confirm(`确定要删除选中的 ${selectedCount} 张图片吗？`)) {
        const selectedIds = visibleItems.value.filter(item => item.selected).map(item => item.id);
        
        items.value = items.value.filter(item => !selectedIds.includes(item.id));
        visibleItems.value = visibleItems.value.filter(item => !selectedIds.includes(item.id));
        filteredItems.value = filteredItems.value.filter(item => !selectedIds.includes(item.id));
        
        updateHasSelected();
        
        if (viewMode.value === 'waterfall') {
          arrangeWaterfallItems();
        }
      }
    };

    // 删除所有项目
    const deleteAll = () => {
      if (items.value.length === 0) return;
      
      if (confirm(`确定要删除全部 ${items.value.length} 张图片吗？`)) {
        items.value = [];
        visibleItems.value = [];
        filteredItems.value = [];
        updateHasSelected();
        isSelecting.value = false;
        page.value = 1; // 重置页码
        allLoaded.value = false; // 重置加载状态
      }
    };

    // 显示预览
    const showPreview = (src: string) => {
      previewLoaded.value = false;
      previewImage.value = src;
      previewVisible.value = true;
    };

    // 更新电视机时间
    const updateTVTime = () => {
      const now = new Date();
      currentTime.value = now.toLocaleTimeString();
    };

    // 处理图片加载
    const handleImageLoad = (id: string, event: Event) => {
      const img = event.target as HTMLImageElement;
      if (!img) return;
      
      const item = visibleItems.value.find(i => i.id === id);
      if (!item) return;
      
      item.naturalWidth = img.naturalWidth;
      item.naturalHeight = img.naturalHeight;
      item.loaded = true;
      item.loading = false;
      
      if (viewMode.value === 'waterfall') {
        arrangeWaterfallItems();
      }
    };

    // 根据容器宽度获取列数
    const getColumnCount = (containerWidth: number) => {
      if (containerWidth > 700) return 4;
      if (containerWidth > 500) return 3;
      return 2;
    };

    // 处理图片加载错误
    const handleImageError = (id: string) => {
      const item = visibleItems.value.find(i => i.id === id);
      if (!item) return;
      
      item.retryCount++;
      
      if (item.retryCount <= 3) {
        item.displaySrc = item.src + `?retry=${item.retryCount}`;
      } else {
        item.displaySrc = DEFAULT_IMAGE;
        item.height = 200;
        item.loaded = true;
        item.loading = false;
      }
      
      if (viewMode.value === 'waterfall') {
        arrangeWaterfallItems();
      }
    };

    // 瀑布流布局算法
    const arrangeWaterfallItems = () => {
      if (viewMode.value !== 'waterfall' || !cardContainer.value) return;
      
      nextTick(() => {
        const container = cardContainer.value!;
        const containerWidth = container.offsetWidth;
        const gap = 10;
        const columnCount = getColumnCount(containerWidth);
        const columnWidth = (containerWidth - (columnCount - 1) * gap) / columnCount;
        const newColumnHeights = Array(columnCount).fill(0);
        const newCardPositions: {[key: string]: {left: number, top: number, width: number}} = {};
        
        filteredItems.value.forEach(item => {
          let minHeight = newColumnHeights[0];
          let minIndex = 0;
          
          for (let i = 1; i < newColumnHeights.length; i++) {
            if (newColumnHeights[i] < minHeight) {
              minHeight = newColumnHeights[i];
              minIndex = i;
            }
          }
          
          const left = minIndex * (columnWidth + gap);
          const top = minHeight;
          
          newCardPositions[item.id] = { 
            left, 
            top, 
            width: columnWidth 
          };
          
          let itemHeight = 200;
          if (item.loaded && item.naturalWidth && item.naturalHeight) {
            const ratio = item.naturalHeight / item.naturalWidth;
            itemHeight = columnWidth * ratio;
          } else if (item.height) {
            itemHeight = item.height;
          }
          
          newColumnHeights[minIndex] += itemHeight + gap;
        });
        
        cardPositions.value = newCardPositions;
        const maxHeight = Math.max(...newColumnHeights);
        container.style.height = `${maxHeight}px`;
      });
    };

    // 打开倒计时模态框
    const openCountdownModal = () => {
      countdownModalVisible.value = true;
    };

    // 倒计时功能 - 单目标
    const startSingleCountdown = async () => {
      if (countdownInterval.value) {
        clearInterval(countdownInterval.value);
      }
      
      const target = new Date(singleTargetTime.value);
      const now = new Date();
      
      if (target <= now) {
        const toast = await toastController.create({
          message: '目标时间必须晚于当前时间',
          duration: 2000,
          color: 'danger'
        });
        await toast.present();
        return;
      }
      
      countdownActive.value = true;
      countdownModalVisible.value = false;
      
      updateSingleCountdown();
      
      countdownInterval.value = setInterval(() => {
        updateSingleCountdown();
      }, 1000);
    };

    const updateSingleCountdown = () => {
      const now = new Date().getTime();
      const target = new Date(singleTargetTime.value).getTime();
      const distance = target - now;
      
      if (distance < 0) {
        stopCountdown();
        alert('倒计时结束！');
        return;
      }
      
      displayDays.value = Math.floor(distance / (1000 * 60 * 60 * 24));
      displayHours.value = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      displayMinutes.value = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      displaySeconds.value = Math.floor((distance % (1000 * 60)) / 1000);
    };

    // 倒计时功能 - 双目标
    const startDualCountdown = async () => {
      if (countdownInterval.value) {
        clearInterval(countdownInterval.value);
      }
      
      const start = new Date(startTime.value);
      const end = new Date(endTime.value);
      
      if (end <= start) {
        const toast = await toastController.create({
          message: '结束时间必须晚于开始时间',
          duration: 2000,
          color: 'danger'
        });
        await toast.present();
        return;
      }
      
      countdownActive.value = true;
      countdownModalVisible.value = false;
      
      updateDualCountdown();
      
      countdownInterval.value = setInterval(() => {
        updateDualCountdown();
      }, 1000);
    };

    const updateDualCountdown = () => {
      const now = new Date().getTime();
      const start = new Date(startTime.value).getTime();
      const end = new Date(endTime.value).getTime();
  
      // 检查当前时间是否在时间范围内
      if (now < start) {
       // 还未到开始时间：显示距离开始的倒计时
        const distance = start - now;
       updateCountdownDisplay(distance);
     } else if (now < end) {
        // 在开始和结束时间之间：显示距离结束的倒计时
        const distance = end - now;
        updateCountdownDisplay(distance);
     } else {
        // 已经超过结束时间：停止倒计时
        stopCountdown();
       alert('倒计时已结束！');
       }
    };

    // 新增辅助函数：更新倒计时显示
    const updateCountdownDisplay = (distance: number) => {
      displayDays.value = Math.floor(distance / (1000 * 60 * 60 * 24));
      displayHours.value = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      displayMinutes.value = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      displaySeconds.value = Math.floor((distance % (1000 * 60)) / 1000);
    };

    // 停止倒计时
    const stopCountdown = () => {
      if (countdownInterval.value) {
        clearInterval(countdownInterval.value);
        countdownInterval.value = null;
      }
      countdownActive.value = false;
    };

    // 处理滚动事件 - 实现懒加载
    const handleScroll = (event: any) => {
      const scrollElement = event.target;
      const scrollPosition = scrollElement.scrollTop;
      const scrollHeight = scrollElement.scrollHeight;
      const containerHeight = scrollElement.clientHeight;
      
      // 当滚动到底部附近时加载更多（距离底部100px）
      if (scrollHeight - (scrollPosition + containerHeight) < 100) {
        loadMoreItems();
      }
    };

    // 加载更多项目
    const loadMoreItems = () => {
      if (isLoading.value || allLoaded.value) return;
      
      isLoading.value = true;
      
      // 模拟网络请求延迟
      setTimeout(() => {
        const newItems = generateItems(10, items.value.length);
        items.value.push(...newItems);
        visibleItems.value.push(...newItems);
        filteredItems.value = [...items.value]; // 更新过滤列表
        
        isLoading.value = false;
        page.value++;
        
        // 如果加载到第5页，标记为全部加载完成
        if (page.value >= 5) {
          allLoaded.value = true;
        }
        
        // 重新布局瀑布流
        if (viewMode.value === 'waterfall') {
          arrangeWaterfallItems();
        }
      }, 1000);
    };
    
    // 处理搜索输入（带防抖）
    const handleSearchInput = () => {
      showSuggestions.value = true;
      
      // 清除之前的定时器
      if (searchTimeout.value) {
        clearTimeout(searchTimeout.value);
      }
      
      // 设置防抖定时器（300毫秒）
      searchTimeout.value = setTimeout(() => {
        updateSuggestions();
      }, 300);
    };
    
    // 更新搜索建议
    const updateSuggestions = () => {
      if (!searchQuery.value) {
        // 如果没有搜索词，显示历史记录
        filteredSuggestions.value = [...searchHistory.value].reverse();
        return;
      }
      
      const query = searchQuery.value.toLowerCase();
      
      // 过滤建议：匹配历史记录和标签
      filteredSuggestions.value = [
        ...searchHistory.value,
        ...allSuggestions.value
      ]
      .filter((suggestion, index, self) => 
        self.indexOf(suggestion) === index && // 去重
        suggestion.toLowerCase().includes(query) // 匹配关键词
      )
      .slice(0, 8); // 最多显示8条
    };
    
    // 应用搜索
    const applySearch = () => {
      if (!searchQuery.value) {
        // 清空搜索时显示所有项目
        filteredItems.value = [...items.value];
        showSuggestions.value = false;
        return;
      }
      
      const query = searchQuery.value.toLowerCase();
      
      // 更新历史记录（不重复添加）
      if (!searchHistory.value.includes(searchQuery.value)) {
        searchHistory.value.push(searchQuery.value);
        // 最多保留10条历史记录
        if (searchHistory.value.length > 10) {
          searchHistory.value.shift();
        }
      }
      
      // 过滤项目：匹配标签
      filteredItems.value = items.value.filter(item => 
        item.tags.some(tag => tag.toLowerCase().includes(query))
      );
      
      showSuggestions.value = false;
      
      // 重新布局瀑布流
      if (viewMode.value === 'waterfall') {
        nextTick(() => {
          arrangeWaterfallItems();
        });
      }
    };
    
    // 选择搜索建议
    const selectSuggestion = (suggestion: string) => {
      searchQuery.value = suggestion;
      applySearch();
    };
    
    // 清空搜索
    const clearSearch = () => {
      searchQuery.value = '';
      filteredItems.value = [...items.value];
      showSuggestions.value = false;
      
      // 重新布局瀑布流
      if (viewMode.value === 'waterfall') {
        nextTick(() => {
          arrangeWaterfallItems();
        });
      }
    };

    // 初始化和清理
    onMounted(() => {
      // 初始布局
      if (viewMode.value === 'waterfall') {
        arrangeWaterfallItems();
      }
      
      // 设置初始时间值
      const now = new Date();
      singleTargetTime.value = new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString();
      startTime.value = now.toISOString();
      endTime.value = new Date(now.getTime() + 2 * 24 * 60 * 60 * 1000).toISOString();
      
      // 初始化电视机时间并每秒更新
      updateTVTime();
      setInterval(updateTVTime, 1000);
      
      // 添加点击事件监听器，点击页面其他区域时关闭搜索建议
      document.addEventListener('click', (e) => {
        const searchContainer = document.querySelector('.search-container');
        if (searchContainer && !searchContainer.contains(e.target as Node)) {
          showSuggestions.value = false;
        }
      });
    });

    onUnmounted(() => {
      stopCountdown();
      document.removeEventListener('click', () => {});
    });

    return {
      items,
      visibleItems,
      filteredItems,
      viewMode,
      isLoading,
      previewVisible,
      previewImage,
      previewLoaded,
      currentTime,
      currentItemTags,
      hasSelected,
      isSelecting,
      cardContainer,
      contentElement,
      countdownModalVisible,
      countdownMode,
      singleTargetTime,
      startTime,
      endTime,
      countdownActive,
      displayDays,
      displayHours,
      displayMinutes,
      displaySeconds,
      searchQuery,
      showSuggestions,
      filteredSuggestions,
      getCardStyle,
      toggleView,
      toggleSelectMode,
      addItem,
      deleteSelected,
      deleteAll,
      showPreview,
      handleCardClick,
      startLongPress,
      endLongPress,
      handleImageLoad,
      handleImageError,
      handlePreviewImageError,
      handleScroll,
      openCountdownModal,
      startSingleCountdown,
      startDualCountdown,
      stopCountdown,
      handleSearchInput,
      applySearch,
      selectSuggestion,
      clearSearch,
      ...icons
    };
  },
    data() {
      return {
        home,
        bagHandle,
        library,
        accessibility,
      };
    },
  });
</script>


<style scoped>
/* 固定工具栏样式 */
.fixed-toolbar {
  position: sticky;
  top: 0;
  z-index: 1000;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  min-height: 56px; /* 确保最小高度 */
  padding: 0; /* 移除内边距 */
}

.card-container {
  padding: 10px;
  position: relative;
  transition: height 0.3s ease;
  min-height: 100px;
  margin-top: 10px; /* 从 60px 改为 10px */
}

/* 网格视图 */
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  grid-gap: 10px;
}

/* 响应式网格 */
@media (max-width: 600px) {
  .grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  }
}

/* 瀑布流视图 */
.waterfall {
  display: block;
}

.gallery-card {
  margin: 0;
  position: relative;
  overflow: hidden;
  border-radius: 8px;
  transition: all 0.3s ease;
  width: 150px;
  height: auto;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  background: #fff;
}

.waterfall .gallery-card {
  width: 100%;
  margin-bottom: 10px;
}

.gallery-card.select-mode {
  cursor: default;
}

.gallery-card:hover:not(.select-mode) {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
}

.gallery-card.selected {
  box-shadow: 0 0 0 3px #3880ff, 0 10px 25px -5px rgba(0, 0, 0, 0.1);
  transform: translateY(-5px) scale(1.02);
  z-index: 10;
}

.gallery-card.not-selected {
  opacity: 0.7;
}

.image-container {
  position: relative;
  overflow: hidden;
  border-radius: 6px;
  background: #f5f5f5;
  min-height: 150px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.7);
  z-index: 10;
}

.skeleton-placeholder {
  width: 100%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  border-radius: 6px;
}

@keyframes shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

.lazy-image {
  width: 100%;
  height: auto;
  display: block;
  transition: opacity 0.3s ease;
  opacity: 0;
  min-height: 150px;
}

.lazy-image.loaded {
  opacity: 1;
}

/* 电视机预览样式 */
.tv-preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px;
  background: linear-gradient(to bottom, #2c3e50, #1a1a2e);
}

.tv-frame {
  position: relative;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.tv-screen {
  position: relative;
  width: 90%;
  padding-top: 56.25%; /* 16:9 宽高比 */
  margin: 0 auto;
  background-color: #111;
  border: 15px solid #333;
  border-radius: 10px;
  box-shadow: 0 0 50px rgba(0, 0, 0, 0.7);
  overflow: hidden;
}

.tv-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
  opacity: 0;
  transition: opacity 0.5s ease;
}

.tv-image.loaded {
  opacity: 1;
}

.tv-spinner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  z-index: 10;
}

.tv-stand {
  position: relative;
  width: 40%;
  height: 30px;
  background: linear-gradient(to bottom, #555, #333);
  margin: 0 auto;
  border-radius: 0 0 8px 8px;
  box-shadow: 0 10px 20px rgba(0,0,0,0.5);
}

.tv-time {
  position: absolute;
  bottom: 10px;
  right: 15px;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 0.9rem;
  z-index: 10;
}

/* 标签容器 */
.tags-container {
  color: white;
  position: absolute;
  bottom: 100%;
  left: 0;
  right: 0;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 2px;
  padding: 0px;
  z-index: 20;
   /* 新增：设置标签文字为白色 */
  ion-chip {
    --color: white; /* 文字颜色 */
    --background: rgba(0, 0, 0, 0.5); /* 背景半透明 */
    ion-label {
      color: white; /* 确保文字颜色为白色 */
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.7); /* 添加文字阴影增强可读性 */
    }
  }
}

.tv-controls {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  width: 100%;
}

.tv-button {
  --background: #ff416c;
  --background-hover: #ff4b2b;
  --color: white;
  max-width: 200px;
}

/* 倒计时头部显示 */
.countdown-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #ddd;
}

.time-display {
  display: flex;
  justify-content: center;
  margin: 5px 0;
}

.time-unit {
  margin: 0 8px;
  min-width: 50px;
  text-align: center;
}

.time-value {
  display: block;
  font-size: 1.5rem;
  font-weight: bold;
  color: #3880ff;
}

.time-label {
  display: block;
  font-size: 0.8rem;
  color: #666;
}

/* 倒计时模态框 */
.countdown-modal-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.countdown-content {
  padding: 20px;
}

.countdown-option {
  margin-top: 20px;
}

ion-segment {
  margin-bottom: 15px;
}

/* 搜索框样式 */
.search-container {
  position: relative;
  flex: 1;
  margin: 0 10px;
}

.custom-searchbar {
  padding: 10;
  --border-radius: 20px;
  --box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.suggestions-box {
  position: fixed; /* 改为固定定位 */
  top: 120px; /* 根据工具栏高度调整 */
  left: 20px;
  right: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  z-index: 1200; /* 提高层级 */
  max-height: 300px;
  overflow-y: auto;
}

.suggestion-item {
  padding: 12px 15px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background 0.2s;
}

.suggestion-item:hover {
  background: #f5f5f5;
}

.suggestion-item ion-icon {
  margin-right: 10px;
  color: #888;
}

.no-suggestions {
  padding: 15px;
  text-align: center;
  color: #999;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .time-unit {
    margin: 0 5px;
    min-width: 40px;
  }
  
  .time-value {
    font-size: 1.2rem;
  }
  
  .tv-screen {
    width: 95%;
    border-width: 10px;
  }
  
  .tv-stand {
    width: 50%;
  }
  
  /* 在小屏幕上调整搜索框位置 */
  ion-toolbar {
    flex-wrap: wrap;
    padding: 5px 0; /* 减少内边距 */
  }
  
  .search-container {
    order: 3;
    width: 100%;
    margin: 5px 0 0;
  }
  
  .card-container {
    margin-top: 10px; /* 为固定工具栏留出更多空间 */
  }
}

@media (max-width: 480px) {
  .tv-screen {
    border-width: 8px;
  }
  
  .tv-time {
    font-size: 0.8rem;
  }
  
  .fixed-toolbar {
    padding: 5px 0;
  }
}
</style>
[file content end]